package com.fywsy.fyweb.service;

import com.fywsy.fyweb.entity.*;
import com.fywsy.fyweb.entity.projection.GameDailyStatsProjection;
import com.fywsy.fyweb.repository.*;
import com.fywsy.fyweb.utils.TextUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class AdminServie {

    @Autowired
    private GameRepository gameRepository;


    @Autowired
    GamePicRepository gamePicRepository;

    @Autowired
    DownloadRepository downloadRepository;

    @Autowired
    GameLinkRepository gameLinkRepository;

    @Autowired
    ContactRepository contactRepository;

    @Autowired
    QufuRepository qufuRepository;

    @Autowired
    GongnengRepository gongnengRepository;

    @Autowired
    ItemRepository itemRepository;

    @Autowired
    SendLogRepository sendLogRepository;

    @Transactional
    public String saveGame(RequestSaveGame request) {
        boolean isAdd = true;
        if (request.game.id != null) { //编辑
            isAdd = false;
        }
        if (isAdd) {
            Game old = gameRepository.findFirstByEnableAndName(true, request.game.name);//新增时校验名字重复
            if (old != null) return "名字已存在!";
        }

        Set<Long> gids = request.gongneng.stream().filter(item -> item.id == null).map(Gongneng::getGid).collect(Collectors.toSet());//新增的gid
        List<Gongneng> allByGidIn = gongnengRepository.findAllByGidIn(gids);
        if (allByGidIn != null && allByGidIn.size() > 0) {
            return "功能ID重复!";
        }
        // tips换号改</br>
        request.game.detailTips = replaceLineBreaks(request.game.detailTips);
        request.game.backendTips = replaceLineBreaks(request.game.backendTips);
        request.game.cdkTips = replaceLineBreaks(request.game.cdkTips);
        request.game.updateTime = LocalDateTime.now();
        gameRepository.save(request.game);

        //保存游戏截图
        if (request.gamePic != null) {
            if (!isAdd || request.gamePic.size() > 0) {
                if (!isAdd) {
                    Set<Long> ids = request.gamePic.stream().filter(item -> item.id != null).map(GamePic::getId).collect(Collectors.toSet());
                    if (ids.isEmpty()) {
                        gamePicRepository.deleteByGameId(request.game.id);
                    } else {
                        gamePicRepository.deleteByGameIdAndIdNotIn(request.game.id, ids);
                    }
                }
                request.gamePic.forEach(i -> i.gameId = request.game.id);
                gamePicRepository.saveAll(request.gamePic);
            }

        }

        // 保存联系方式
        if (request.contact != null) {
            if (!isAdd || request.contact.size() > 0) {
                if (!isAdd) {
                    Set<Long> ids = request.contact.stream().filter(item -> item.id != null).map(Contact::getId).collect(Collectors.toSet());
                    if (ids.isEmpty()) {
                        contactRepository.deleteByGameId(request.game.id);
                    } else {
                        contactRepository.deleteByGameIdAndIdNotIn(request.game.id, ids);
                    }

                }
                request.contact.forEach(i -> i.gameId = request.game.id);
                contactRepository.saveAll(request.contact);
            }

        }

        //保存游戏外链
        if (request.gameLink != null) {
            if (!isAdd || request.gameLink.size() > 0) {
                if (!isAdd) {
                    Set<Long> ids = request.gameLink.stream().filter(item -> item.id != null).map(GameLink::getId).collect(Collectors.toSet());
                    if (ids.isEmpty()) {
                        gameLinkRepository.deleteByGameId(request.game.id);
                    } else {
                        gameLinkRepository.deleteByGameIdAndIdNotIn(request.game.id, ids);
                    }

                }
                request.gameLink.forEach(i -> i.gameId = request.game.id);
                gameLinkRepository.saveAll(request.gameLink);
            }

        }


        //保存下载连接
        if (request.downloadUrl != null) {
            if (!isAdd || request.downloadUrl.size() > 0) {
                if (!isAdd) {
                    Set<Long> ids = request.downloadUrl.stream().filter(item -> item.id != null).map(DownloadUrl::getId).collect(Collectors.toSet());
                    if (ids.isEmpty()) {
                        downloadRepository.deleteByGameId(request.game.id);
                    } else {
                        downloadRepository.deleteByGameIdAndIdNotIn(request.game.id, ids);
                    }

                }
                request.downloadUrl.forEach(i -> i.gameId = request.game.id);
                downloadRepository.saveAll(request.downloadUrl);
            }

        }

        // 保存区服
        if (request.qufu != null) {
            if (!isAdd || request.qufu.size() > 0) {
                if (!isAdd) {
                    Set<Long> ids = request.qufu.stream().filter(item -> item.id != null).map(Qufu::getId).collect(Collectors.toSet());
                    if (ids.isEmpty()) {
                        qufuRepository.deleteByGameId(request.game.id);
                    } else {
                        qufuRepository.deleteByGameIdAndIdNotIn(request.game.id, ids);
                    }

                }
                request.qufu.forEach(i -> i.gameId = request.game.id);
                qufuRepository.saveAll(request.qufu);
            }

        }

        // 保存功能及道具
        if (request.gongneng != null) {
            if (!isAdd || request.gongneng.size() > 0) {
                if (!isAdd) {
                    Set<Long> ids = request.gongneng.stream().filter(item -> item.id != null).map(Gongneng::getGid).collect(Collectors.toSet());
                    if (ids.isEmpty()) {
                        gongnengRepository.deleteByGameId(request.game.id);
                        itemRepository.deleteByGameId(request.game.id);//删除时，同时删除道具
                    } else {
                        gongnengRepository.deleteByGameIdAndGidNotIn(request.game.id, ids);
                        itemRepository.deleteByGameIdAndGongnengIdNotIn(request.game.id, ids);//删除时，同时删除道具
                    }

                }

                Set<Gongneng> addGongenngs = request.gongneng.stream().filter(item -> item.id == null).collect(Collectors.toSet());
                request.gongneng.forEach(i -> i.gameId = request.game.id);
                gongnengRepository.saveAll(request.gongneng);

                //保存道具,只可以新增 不可以修改,你可以删了再加
                if (!addGongenngs.isEmpty()) {
                    Gson gson = new Gson();
                    List<Item> collect = addGongenngs.stream().filter(i -> !TextUtils.isEmpty(i.itemsJson))
                            .flatMap(i -> {
                                List<Item> itemsTemp = gson.fromJson(i.itemsJson, new TypeToken<List<Item>>() {
                                }.getType());
                                itemsTemp.forEach(j -> {
                                    j.gameId = request.game.id;
                                    j.gongnengId = i.gid;
                                    j.enable = true;
                                    j.max = i.max;
                                });
                                return itemsTemp.stream();
                            }).toList();

                    itemRepository.saveAll(collect);
                }
            }

        }

        return isAdd ? "新增成功" : "更新成功";
    }


    /**
     * 获取游戏详情 用于编辑
     *
     * @param gameId
     * @return
     */
    public RequestSaveGame getGameDetail(long gameId) {
        RequestSaveGame resp = new RequestSaveGame();
        resp.game = gameRepository.findById(gameId).get();
        resp.qufu = qufuRepository.findAllByGameId(gameId);
        resp.gameLink = gameLinkRepository.findAllByGameId(gameId);
        resp.gamePic = gamePicRepository.findAllByGameId(gameId);
        resp.downloadUrl = downloadRepository.findAllByGameId(gameId);
        resp.contact = contactRepository.findAllByGameId(gameId);
        resp.gongneng = gongnengRepository.findAllByGameId(gameId);
        resp.gongneng.stream().filter(i -> i.req).forEach(i -> {
            //计算功能下面的物品数量，itemCount>0的功能 不允许编辑物品，需要去单独页面编辑
            i.itemCount = itemRepository.countByGameIdAndGongnengId(gameId, i.id);
        });
        resp.game.detailTips = replaceLineBreaks(resp.game.detailTips);
        resp.game.backendTips = replaceLineBreaks(resp.game.backendTips);
        resp.game.cdkTips = replaceLineBreaks(resp.game.cdkTips);
        return resp;
    }

    public ResponseEntity<String> updateGame(Game game) {
        if (game.id == null) return ResponseEntity.badRequest().body("参数错误");
        Game dbGame = gameRepository.findById(game.id).orElse(null);
        if (dbGame == null) {
            return ResponseEntity.badRequest().body("游戏不存在");
        }
        if (game.enable != null) dbGame.enable = game.enable;
        if (game.visable != null) dbGame.visable = game.visable;
        if (game.externalRead != null) dbGame.externalRead = game.externalRead;
        gameRepository.save(dbGame);
        return ResponseEntity.ok("操作成功");
    }

    /**
     * 获取游戏列表
     *
     * @return
     */
    public List<Game> getGames() {
        List<Game> games = gameRepository.findAll(Sort.by(Sort.Direction.DESC, "enable").and(Sort.by(Sort.Direction.DESC, "id")));
        List<GameDailyStatsProjection> gameDailyStats = sendLogRepository.findGameDailyStatsNative();
        
        // 将gameDailyStats关联到对应的games中
        for (Game game : games) {
            for (GameDailyStatsProjection stats : gameDailyStats) {
                if (game.id.equals(stats.getGameId())) {
                    game.gameDailyStats = stats;
                    break;
                }
            }
        }
        
        return games;
    }


    public ResponseAdminItems getItemsByGameId(Long gameId, String word) {
        ResponseAdminItems resp = new ResponseAdminItems();
        resp.items = itemRepository.findAllByGameIdAndNContaining(gameId, word);
        resp.gongnengs = gongnengRepository.findAllByEnableAndReqAndGameIdOrderByWeightDesc(true, true, gameId);
        return resp;
    }

    public ResponseEntity updateItem(Item item) {
        try {
            itemRepository.save(item);
            return ResponseEntity.ok("更新成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    private String replaceLineBreaks(String text) {
        if (!TextUtils.isEmpty(text)) {
            if (text.contains("<br/>")) {
                return text.replaceAll("<br/>", "\n");
            }
            return text.replaceAll("(\r\n|\n)", "<br/>");
        }
        return null;
    }

}
